<?php

namespace App\Services\Applet\User;

use App\Exceptions\UserException;
use App\Helpers\MvcHelper;
use Exception;

class AddressService extends BaseUserService
{

    /**
     * 我的地址列表
     * @return array
     * @throws Exception
     */
    public function list(): array
    {
        // 查询我的地址
        $addressList = $this->getUserAddressModel()->list([
            'id', 'receive_name', 'receive_tel', 'area_info', 'address', 'province_id', 'city_id', 'region_id', 'is_default',
        ]);

        $provinceIds = array_column($addressList, 'province_id');
        $cityIds = array_column($addressList, 'city_id');
        $regionIds = array_column($addressList, 'region_id');


        $areaIds = array_merge($provinceIds, $cityIds, $regionIds);
        // 查询省市区
        $areaList = $this->getAreaModel()->getAreaNameListByCodeList($areaIds);
        $areaListMap = array_column($areaList, 'name', 'id');

        $list = [];
        foreach ($addressList as $item) {
            $province = $areaListMap[$item['province_id']] ?? '';
            $city = $areaListMap[$item['city_id']] ?? '';
            $region = $areaListMap[$item['region_id']] ?? '';
            $address = $province . $city . $region . $item['area_info'] . $item['address'];
            $list[] = [
                'id' => $item['id'],
                'receiveName' => $item['receive_name'],
                'receiveTel' => $item['receive_tel'],
                'address' => $address,
                'isDefault' => $item['is_default'],
            ];
        }

        return [
            'list' => $list,
        ];
    }

    /**
     * 地址详情
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function detail(array $params): array
    {
        // 查询地址
        $detail = $this->getUserAddressModel()->getItemById($params['id'], [
            'id', 'receive_name', 'receive_tel', 'area_info', 'address', 'province_id', 'city_id', 'region_id', 'province_id', 'city_id', 'region_id', 'is_default',
        ]);

        $areaIds = [$detail['province_id'], $detail['city_id'], $detail['region_id']];
        // 查询地址
        $areaList = $this->getAreaModel()->getAreaNameListByCodeList($areaIds);
        $areaListMap = array_column($areaList, 'name', 'id');

        return [
            'id' => $detail['id'],
            'provinceId' => $detail['province_id'],
            'province' => $areaListMap[$detail['province_id']] ?? '',
            'cityId' => $detail['city_id'],
            'city' => $areaListMap[$detail['city_id']] ?? '',
            'regionId' => $detail['region_id'],
            'region' => $areaListMap[$detail['region_id']] ?? '',
            'areaInfo' => $detail['area_info'],
            'address' => $detail['address'],
            'isDefault' => $detail['is_default'],
        ];
    }

    /**
     * 添加地址
     * @return void
     * @throws Exception
     */
    public function create(array $params)
    {
        // 查询是否有用户地址
        $userAddress = $this->getUserAddressModel()->getItemByUserId(MvcHelper::getLoginUserId());

        $isDefault = 0;
        if (empty($userAddress)) { // 第一次添加地址设置为默认地址
            $isDefault = 1;
        }

        $createAddress = [
            'user_id' => MvcHelper::getLoginUserId(),
            'receive_name' => $params['receiveName'],
            'receive_tel' => $params['receiveTel'],
            'area_info' => $params['areaInfo'] ?? '',
            'address' => $params['address'] ?? '',
            'province_id' => $params['provinceId'],
            'city_id' => $params['cityId'],
            'region_id' => $params['regionId'],
            'is_default' => $isDefault,
        ];

        // 添加地址
        $this->getUserAddressModel()->addItem($createAddress);
    }

    /**
     * 更新地址
     * @return void
     * @throws UserException
     * @throws Exception
     */
    public function update(array $params)
    {
        // 查询是否有用户地址
        $userAddress = $this->getUserAddressModel()->getItemByUserId(MvcHelper::getLoginUserId());
        if (empty($userAddress)) {
            throw new UserException('用户地址不存在', UserException::CODE_1004);
        }

        $updateAddress = [];
        if (!empty($params['receiveName'])) {
            $updateAddress['receive_name'] = $params['receiveName'];
        }
        if (!empty($params['receiveTel'])) {
            $updateAddress['receive_tel'] = $params['receiveTel'];
        }
        if (!empty($params['areaInfo'])) {
            $updateAddress['area_info'] = $params['areaInfo'];
        }
        if (!empty($params['address'])) {
            $updateAddress['address'] = $params['address'];
        }
        if (!empty($params['provinceId'])) {
            $updateAddress['province_id'] = $params['provinceId'];
        }
        if (!empty($params['cityId'])) {
            $updateAddress['city_id'] = $params['cityId'];
        }
        if (!empty($params['regionId'])) {
            $updateAddress['region_id'] = $params['regionId'];
        }
        if (!empty($params['isDefault'])) {
            $updateAddress['is_default'] = $params['isDefault'];
        }

        if (!empty($updateAddress)) {
            // 将其他默认的改为取消默认
            $this->getUserAddressModel()->updateIsDefaultNoByUserId(MvcHelper::getLoginUserId());
            // 更新地址
            $this->getUserAddressModel()->updateItemById($params['id'], $updateAddress);
        }
    }

    /**
     * 删除地址
     * @param array $params
     * @return void
     * @throws UserException
     * @throws Exception
     */
    public function delete(array $params)
    {
        // 查询是否有用户地址
        $userAddress = $this->getUserAddressModel()->getItemByUserId(MvcHelper::getLoginUserId());
        if (empty($userAddress)) {
            throw new UserException('用户地址不存在', UserException::CODE_1004);
        }


        // 更新地址
        $this->getUserAddressModel()->deleteItemById($params['id']);
    }

}
